/*
Pickin' Open Sticks
Homepage:   http://code.google.com/p/pickin-open-sticks/
License:    GNU GPL v3 http://www.gnu.org/licenses/gpl.html
*/

/**
 * SoundManager methods.
 * @author Terry Brashaw
 * @date Oct 5
 */

#include "SoundManager.h"
namespace pe
{

    SoundManager::SoundManager() {
        Initialize();
    }

    SoundManager::~SoundManager() {
        // Use stl::std::vector's Clear function
        m_soundWrap.clear();
    }

    void SoundManager::Initialize() {
        // Add all the sounds that are going to be used in the game.
        // void AddSound(const string& filename,const string& identifier, bool loops);
        AddSound("assets/sfx/pick_up_stick.wav", "pick", false);
    }

    void SoundManager::AddSound(const std::string& relPath, const std::string& sId, bool loops) {
        // TODO: Review "new". Is this valid in C++?  Memory issues?
        m_soundWrap.push_back(new SoundWrap(relPath, sId, m_soundWrap.size(), loops));
    }

    /**
     * Returns the sf::SoundBuffer item being stored so other objects that
     * may have a Sound object can set it.
     * */
    sf::SoundBuffer& SoundManager::GetSoundBuffer(const std::string& sId) {
        int index = FindIndex(sId);

        if (index >= 0)
            return m_soundWrap[index]->m_sndbuff;
        else
            return m_soundWrap[0]->m_sndbuff;
    }

    sf::SoundBuffer& SoundManager::GetSoundBuffer(int iId) {
        if (iId < (int) m_soundWrap.size() && iId >= 0)
            return m_soundWrap[iId]->m_sndbuff;

        // iId is out of bounds, return default
        return m_soundWrap[0]->m_sndbuff;
    }

    /**
     * Plays sound file based on identifier given
     * */
    void SoundManager::PlaySound(const std::string& sId) {
        int index = FindIndex(sId);

        if (index >= 0)
            m_soundWrap[index]->m_snd.Play();
    }

    void SoundManager::PlaySound(int iId) {
        if (iId < (int) m_soundWrap.size() && iId >= 0)
            m_soundWrap[iId]->m_snd.Play();
    }

    /**
     * Returns the index of the desired asset based on the string passed
     * @param sId string			string identifier of the asset
     * */
    int SoundManager::FindIndex(const std::string& sId) {
        int index = -1;
        for (int i = 0; i < (int) m_soundWrap.size(); i++) {
            if (m_soundWrap[i]->m_name == sId) {
                index = i;
                break;
            }
        }

        return index;
    }
}
